<template>
  <base-layout>
    <div class="class-manage">
      <div class="page-header">
        <h2>班级管理</h2>
        <div class="header-actions">
          <a-button type="primary" @click="handleAddClass">
            <template #icon><plus-outlined /></template>
            新增班级
          </a-button>
        </div>
      </div>

      <div class="search-area">
        <a-input-search
          v-model:value="searchText"
          placeholder="搜索班级名称"
          style="width: 300px"
          @search="onSearch"
        />
        <a-select
          v-model:value="filterGrade"
          style="width: 120px"
          placeholder="年级"

          
        >
          <a-select-option value="">全部年级</a-select-option>
          <a-select-option value="XXXX">XXXX级</a-select-option>
          <a-select-option value="2024">2024级</a-select-option>
          <a-select-option value="2023">2023级</a-select-option>
          <a-select-option value="2022">2022级</a-select-option>
          <a-select-option value="2021">2021级</a-select-option>
        </a-select>
        <a-select
          v-model:value="filterMajor"
          style="width: 150px"
          placeholder="专业"

          
        >
          <a-select-option value="">全部专业</a-select-option>
          <a-select-option value="xxxx">xxxx</a-select-option>
          <a-select-option value="计算机科学与技术">计算机科学与技术</a-select-option>
          <a-select-option value="软件工程">软件工程</a-select-option>
          <a-select-option value="信息安全">信息安全</a-select-option>
          <a-select-option value="电子工程">电子工程</a-select-option>
          <a-select-option value="通信工程">通信工程</a-select-option>
          <a-select-option value="物联网工程">物联网工程</a-select-option>
          

        </a-select>
      </div>

      <a-table
        :columns="columns"
        :data-source="classList"
        :loading="loading"
        :pagination="pagination"
        @change="handleTableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'action'">
            <a-space>
              <a @click="handleEdit(record)">编辑</a>
              <a-divider type="vertical" />
              <a @click="handleView(record)">查看</a>
              <a-divider type="vertical" />
              <a-popconfirm
                title="确定要删除这个班级吗？"
                @confirm="handleDelete(record)"
              >
                <a class="danger-link">删除</a>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </div>
  </base-layout>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import BaseLayout from '@/components/layout/BaseLayout.vue'

import { getClasses, searchClasses, deleteClass } from '@/api/classes'

const router = useRouter()
const searchText = ref('')
const filterGrade = ref('')
const filterMajor = ref('')
const loading = ref(false)
const classList = ref([])

const columns = [
  {
    title: '班级名称',
    dataIndex: 'name',
    key: 'name',
  },
  {
    title: '年级',
    dataIndex: 'grade',
    key: 'grade',
  },
  {
    title: '专业',
    dataIndex: 'major',
    key: 'major',
  },
  {
    title: '学业导师',
    dataIndex: 'teacher',
    key: 'teacher',
  },
  {
    title: '学生人数',
    dataIndex: 'studentCount',
    key: 'studentCount',
  },
  {
    title: '操作',
    key: 'action',
    fixed: 'right',
    width: 200,
  },
]

const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0,
  showTotal: (total) => `共 ${total} 条记录`,
})

// 加载班级列表
const loadClassList = async () => {
  loading.value = true
  
  try {
    const res = await getClasses();
    classList.value = res?.content?.map(item => ({
      id: item.id,
      name: item.className,
      grade: item.grade,
      major: item.major,
      teacher: item.tutor,
      studentCount: item.studentCount
    })) || [];
    
    pagination.value.total = res?.totalElements || classList.value.length;
  } catch (error) {
    classList.value = [];
  } finally {
    loading.value = false;
  }
}

// 共享的获取班级数据函数【搜索和分页共有的部分】
const fetchClassData = async (params, updatePagination = true) => {
  loading.value = true;
  try {
    const res = await searchClasses(params);
    
    // 处理返回数据
    classList.value = res?.content?.map(item => ({
      id: item.id,
      name: item.className,
      grade: item.grade,
      major: item.major,
      teacher: item.tutor,
      studentCount: item.studentCount
    })) || [];
    
    // 更新分页信息
    if (updatePagination) {
      if (params.page !== undefined) {
        pagination.value.current = params.page + 1; // 后端从0开始，前端从1开始
      }
      if (params.size !== undefined) {
        pagination.value.pageSize = params.size;
      }
      pagination.value.total = res?.totalElements || classList.value.length;
    }
    
    return res;
  } catch (error) {
    console.error('获取班级数据失败:', error);
    message.error('获取班级数据失败');
    classList.value = [];
    throw error;
  } finally {
    loading.value = false;
  }
};

// 搜索
const onSearch = async () => {
  // 构建搜索参数
  const params = {
    className: searchText.value || undefined,
    grade: filterGrade.value || undefined,
    major: filterMajor.value || undefined,
    page: 0, // 搜索时重置到第一页
    size: pagination.value.pageSize
  };
  
  // 使用共享函数获取数据
  await fetchClassData(params);
}

// 表格变化处理
const handleTableChange = async (pag) => {
  // 构建分页参数，保留搜索条件
  const params = {
    className: searchText.value || undefined,
    grade: filterGrade.value || undefined,
    major: filterMajor.value || undefined,
    page: pag.current - 1, // API页码从0开始
    size: pag.pageSize
  };
  
  // 使用共享函数获取数据
  await fetchClassData(params);
}

// 新增班级
const handleAddClass = () => {
  console.log('跳转到新增班级页面')
  router.push({ path: '/class-create' })
}

// 编辑班级
const handleEdit = (record) => {
  console.log('跳转到编辑班级页面:', record.id)
  router.push({ path: `/class-edit/${record.id}` })
}

// 查看班级
const handleView = (record) => {
  console.log('跳转到班级详情页面:', record.id)
  router.push({ path: `/class-detail/${record.id}` })
}

// 删除班级
const handleDelete = async (record) => {
  try {
    await deleteClass(record.id);
    message.success('删除成功');
    loadClassList();
    // 刷新列表数据
  } catch (error) {
    message.error('删除失败: ' + (error.message || '未知错误'));
  }
}

onMounted(() => {
  loadClassList()
})
</script>

<style scoped>
.class-manage {
  padding: 24px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.header-actions {
  display: flex;
  gap: 16px;
}

.search-area {
  margin-bottom: 24px;
  display: flex;
  gap: 16px;
}

.danger-link {
  color: #ff4d4f;
}

.danger-link:hover {
  color: #ff7875;
}
</style> 